package com.example.demo.auth;


import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.entity.TToken;
import com.example.demo.service.TokenService;

@Service
public class AuthService {
	
	private final static Logger log = LoggerFactory.getLogger(AuthService.class);

	public static final AuthService me = new AuthService();
	
	@Autowired
	TokenService tokenService;
	
	/**
	 * 鉴权
	 * @param appid
	 * @param sign
	 * @param requset
	 * @return
	 */
	public String checkSyncAuth(String appid, String sign, HttpServletRequest requset) {
		try {
			if (StringUtils.isBlank(sign)) {
				return TokenResult.gettokenResult().getInvalidSignMsg();
			}
			// 一.判断token 是否过期
			TToken token = tokenService.findByAppId(appid);
			if (token == null) {
				return TokenResult.gettokenResult().getInvalidAppidMsg();
			}
			if (isExpired(token.getExpire())) {// token过期
				return TokenResult.gettokenResult().getIsExpiredMsg();
			}
			// 1.鉴权
			String signUrl = AuthenticationKit.getSignUrl(requset, "sign");
			String signUrlEncode = AuthenticationKit.signUrlEncode(signUrl, token.getToken());
			// 签名无
			if (StringUtils.isBlank(sign) || !sign.equals(signUrlEncode)) {
				return TokenResult.gettokenResult().getInvalidSignMsg();
			}
			/* 业务逻辑处理部分 */
			return null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return TokenResult.gettokenResult().getErrMsg();
	}
	/**
	 * 是否过期
	 * @return true已过期
	 */
	public boolean isExpired(Long expire) {
		return expire < (System.currentTimeMillis()/1000);
	}


}
